package com.bj58.migrate.task;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import com.bj58.migrate.Config;
import org.apache.log4j.Logger;

import com.bj58.migrate.condition.ConditionReader;
import com.bj58.migrate.update.DataHandler;

public class Task{

    private Logger logger = Logger.getLogger( Task.class );

    private DataHandler updateHandler;
    private ConditionReader conditionReader;

    private String[] args;

    public Task( String[] args ){

        this.args = args;

        String readerConfig = args[ 0 ];
        String handlerConfig = args[ 1 ];

        try{

            Class< ? > readerClass = Class.forName( Config.getProperty( readerConfig ) );
            Class< ? > handlerClass = Class.forName( Config.getProperty( handlerConfig ) );

            ConditionReader reader = ( ConditionReader )readerClass.newInstance();
            DataHandler handle = ( DataHandler )handlerClass.newInstance();

            this.conditionReader = reader;
            this.updateHandler = handle;
        }
        catch( Exception ex ){
            ex.printStackTrace();
        }
    }

    public void run( String[] args ){

        if( this.conditionReader != null && this.updateHandler != null ){
            File[] files = this.conditionReader.getConditionFileList( args );
            if( files != null && files.length > 0 ){
                for( File file : files ){
                    // 加入日志
                    logger.info( "Process " + args[ 2 ] + ": " + file.getName() );
                    handleData( file );
                }
            }
        }
    }

    protected void handleData( File file ){

        if( file != null ){
            String s = null;
            try{
                BufferedReader br = new BufferedReader( new InputStreamReader( new FileInputStream( file ) ) );
                while( ( s = br.readLine() ) != null ){
                    logger.info( "Update..." + file.getName() + "..." + s );
                    try{
                        updateHandler.handle( s.trim(), args );
                    }
                    catch( Exception e ){
                        logger.error( "Condition:" + s + " Error", e );
                    }
                }
                br.close();
            }
            catch( Exception e ){
                e.printStackTrace();
            }
        }
    }

    public ConditionReader getConditionReader(){

        return conditionReader;
    }

    public DataHandler getDataUpdateHandler(){

        return updateHandler;
    }
}
